package com.dodock.android.banglapapers.ui;

import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dodock.android.banglapapers.BanglaNews;
import com.dodock.android.banglapapers.Category;
import com.dodock.android.banglapapers.ComplexScriptHelper;
import com.dodock.android.banglapapers.InternetConnectivity;
import com.dodock.android.banglapapers.MyApplication;
import com.dodock.android.banglapapers.R;
import com.dodock.android.banglapapers.Utility;
import com.dodock.android.banglapapers.WebServerOperation;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

public class NewsCategoryActivity extends BaseActivity{
	
	private ProgressDialog progressDialog;
	private boolean bError = false;
	private String newspaperId = "";
	private String language = "";
	private Typeface fontBN;
	private Typeface fontEN;
	private Vector<Category> categoryList;
    private String paperName;
    
    private Tracker mGaTracker;
	private GoogleAnalytics mGaInstance;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
				
		//Google Analytics
		try{
		    mGaInstance = GoogleAnalytics.getInstance(this);
		    mGaTracker = mGaInstance.getTracker(getResources().getString(R.string.ga_trackingId));
		}
		catch (Exception e) {
		}
		//--Google Analytics
		
		
		newspaperId = getIntent().getExtras().getString("newsId");
		language = getIntent().getExtras().getString("language");
		paperName = getIntent().getExtras().getString("paperName");
		setContentView(R.layout.news_category);
		fontBN = Typeface.createFromAsset(this.getAssets(), "font/SutonnyMJ.ttf");
		fontEN = Typeface.DEFAULT;
		TextView titleView = (TextView) findViewById(R.id.title);
		if(language.equals("bn")){					
			if(Utility.isOnlyEngCharacters(paperName)){
				titleView.setTypeface(fontEN);
				titleView.setText(paperName);
			}else{
				titleView.setTypeface(fontBN);					
				titleView.setText(ComplexScriptHelper.UnicodeToAnsi(paperName));
			}
		}else{
			titleView.setTypeface(fontEN);
			titleView.setText(paperName);
		}
		
		ImageButton settingsButton = (ImageButton) findViewById(R.id.settingsBtn);
		settingsButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				settingsActivity();
			}
		});
		
		Button topNewsButton = (Button) findViewById(R.id.topNews);
		
		topNewsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewsCategoryActivity.this, TopNewsActivity.class);
				startActivity(intent);
			}
		});

		Button favouritButton = (Button) findViewById(R.id.favorite);
		favouritButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewsCategoryActivity.this, FavouritNewsActivity.class);
				startActivity(intent);
			}
		});

		Button savedNewsButton = (Button) findViewById(R.id.savedNews);
		savedNewsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewsCategoryActivity.this, SavedNewsActivity.class);
				startActivity(intent);
			}
		});
		
		ImageView refreshButton = (ImageView) findViewById(R.id.refresh);
		refreshButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				loadNewsCategory();
			}
		});
		loadNewsCategory();
	}
	
	private void loadNewsCategory() {
		// TODO Auto-generated method stub
		if (InternetConnectivity.isConnectedToInternet(this)) {
			progressDialog = ProgressDialog.show(this, null,
					"Loading. Please wait...", true, false);
			GetNewsCategory getNewsCategory = new GetNewsCategory();
			getNewsCategory.execute();
		} else {
			Toast toast = Toast.makeText(this,
					"Enable mobile network or Wi-Fi to download data",
					Toast.LENGTH_LONG);
			toast.show();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		com.facebook.Settings.publishInstallAsync(this, MyApplication.fb_app_id);
	}

	@Override
	protected void onStart() {
		super.onStart();
		try {
			mGaTracker.sendView(String.format("/%s", newspaperId));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
	
	private class GetNewsCategory extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			getNewsPaperCategoryJson();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			try{
				progressDialog.dismiss();
				progressDialog = null;
				if (!bError){
					showContentView();
				}
			}
			catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	
	private void showContentView() {
		// TODO Auto-generated method stub
		LinearLayout mainContainer = (LinearLayout) findViewById(R.id.newsCategoryMainContainer);

		for (int categoryNO = 0; categoryNO < categoryList.size(); categoryNO++) {
			LinearLayout newsCategoryLayout = (LinearLayout) LayoutInflater.from(
					getBaseContext()).inflate(R.layout.title_logo_horizontle_layout,null);
			TextView display = (TextView) newsCategoryLayout.findViewById(R.id.newsCategoryDisplay);
			if(language.equals("bn")){
				display.setTypeface(fontBN);
				display.setText(ComplexScriptHelper.UnicodeToAnsi(categoryList.elementAt(categoryNO).getDisplay()));
			}else{
				display.setTypeface(fontEN);
				display.setText(categoryList.elementAt(categoryNO).getDisplay());
			}
			final ImageView favouriteImageView = (ImageView) newsCategoryLayout.findViewById(R.id.doUndoFavorite);
			favouriteImageView.setFocusable(true);
			boolean flag = false;
			try{
				flag = BanglaNews.getDatabaseManager().isCategoryExist( newspaperId+ categoryList.elementAt(categoryNO).getKey());
			}
			catch (Exception e) {
			}
			if( flag )
				favouriteImageView.setBackgroundResource(R.drawable.cross);
			else{
				favouriteImageView.setBackgroundResource(R.drawable.plus);
			}

			final int position = categoryNO;
			
			favouriteImageView.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					try{
						boolean flag = BanglaNews.getDatabaseManager().isCategoryExist( newspaperId + categoryList.elementAt(position).getKey());
						if(flag){
							favouriteImageView.setBackgroundResource(R.drawable.plus);
							BanglaNews.getDatabaseManager().removeCategory( newspaperId + categoryList.elementAt(position).getKey());
						}else{
							favouriteImageView.setBackgroundResource(R.drawable.cross);
							ContentValues cv = new ContentValues();
							cv.put("key", categoryList.elementAt(position).getKey());
							cv.put("paper", newspaperId );
							cv.put("display", categoryList.elementAt(position).getDisplay());
							cv.put("paper_key", newspaperId + categoryList.elementAt(position).getKey());
							BanglaNews.getDatabaseManager().addCategoryDB(cv);
						}
						favouriteImageView.invalidate();
					}
					catch (Exception e) {
					}
				}
			});
			
			newsCategoryLayout.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(NewsCategoryActivity.this, NewsListActivity.class);
					intent.putExtra("id", newspaperId);
					intent.putExtra("key", categoryList.elementAt(position).getKey());
					intent.putExtra("language", language);
					intent.putExtra("paperName", paperName);
					startActivity(intent);
				}
			});
			mainContainer.addView(newsCategoryLayout);
		}
	}
	private void getNewsPaperCategoryJson() {
		String urlPath = BanglaNews.BASE_URL + "DDNGetCategories"+"?id="+newspaperId + "&appVersion="+MyApplication.app_version;
		try {
			String serverResonse = WebServerOperation.HTTPrequest(urlPath);
			parseNewsCategoryJSON(serverResonse);
		} catch (Exception e) {
			Log.e("NewsCategoryActivity", "getNewsPaperCategoryJson() : "+e.toString());
			bError = true;
		}
	}
	
	private void parseNewsCategoryJSON(String serverResonse) throws Exception{
		// TODO Auto-generated method stub
		JSONObject jsonObject = new JSONObject(serverResonse);
		JSONArray menuObject1 = jsonObject.getJSONArray("categories");
		categoryList = new Vector<Category>();
		for (int j = 0; j < menuObject1.length(); j++) {
			Category category = new Category();
			String key = menuObject1.getJSONObject(j).getString("key");
			category.setKey(key);
			category.setDisplay(menuObject1.getJSONObject(j).getString("display"));
			category.setPaperName(newspaperId);
			categoryList.add(category);
		}
	}
}
